package com.game.HandleData;

import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * 工具类
 * @author chenlei
 *
 */
public class Tools {
	/**获取某一范围内的随机数*/
    public static int getRandomInt(int min, int max) {  
        if (min > max || min < 0) { 
            return -1;  
        }
        return min + (int) (Math.random() * (max -min + 1));  
    }  
    
    /**
     * byte[]某段元素转int  按照网络字节顺序
     * @param begin
     * @param end
     * @param Pack
     * @return
     */
	public static int ByteToInt(int begin ,int end, byte[] Pack){
		int mask  = 0xff;
		int temp  = 0;
		int res   = 0;
		for(int i=begin;i<=end;i++){
		    res<<=8;
		    temp  = Pack[i]&mask;
		    res  |= temp;
		}
		return res;
	}
	
	/**
	 * int转byte[] 安装网络字节序
	 * 
	 * @param n
	 * @return
	 */
	public static byte[] intToBytes(int n){
	    byte[] b = new byte[4];
	    for(int i = 0;i < 4;i++){
	        b[i]=(byte)(n>>(24-i*8));
	    } 
	   return b;
	 } 
	
	
 	
	/**
	 * MD5 加密方法 返回32位String
	 * 
	 * @param text 需要加密的数据
	 * */
    public static String MD5(String text){
    	StringBuffer md5=new StringBuffer(); 
    	try{
	        MessageDigest md=MessageDigest.getInstance("MD5");   
	        md.update(text.getBytes());   
	        byte[] digest=md.digest();          
	        for(int i=0;i<digest.length;i++){
	        	md5.append(Character.forDigit((digest[i]&0xF0)>>4,16));   
	            md5.append(Character.forDigit((digest[i]&0xF),16));   
	        }   
    	}catch(Exception e){}
        return md5.toString();
    }
    /**
     * 返回时间 
     * @return “yyyy-MM-dd HH:mm:ss”
     */
	public static String getTime()
    {
     	SimpleDateFormat s= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return s.format(Calendar.getInstance().getTime()).toString();
    }
	/**
     * ByteBuffer 数据的复制
     * @param data
     * @return
     */
    public static ByteBuffer copyByteBuffer(ByteBuffer data){
    	byte []dd =  data.array();
    	ByteBuffer datax =  ByteBuffer.allocate(dd.length);
    	datax.put(dd,0,data.limit());
    	datax.flip();
    	return datax;
    }
}
